package tools;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.util.ArrayList;
import java.util.List;


import org.w3c.dom.*;
import org.xml.sax.InputSource;

import entities.Query;

import javax.xml.parsers.*;

public class QueryParser {
	//the path of the query xml file
	private String queryPath;

	public QueryParser(String path){
		this.queryPath = path;
	}
	public String getQueryPath() {
		return queryPath;
	}

	public void setQueryPath(String queryPath) {
		this.queryPath = queryPath;
	}
	
	public List<Query> getQueries() throws Exception{
		
		File f=new File(this.queryPath);
		if(f.exists()){
			DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance(); 
			DocumentBuilder builder=factory.newDocumentBuilder(); 
			
			String content = DocRetriever.getFileContents(this.queryPath);
			//content replace 
			//content = content.replaceAll("&", "&amp;");
			Document doc = builder.parse((new InputSource(new ByteArrayInputStream(content.getBytes("utf-8"))))); 
			ArrayList<Query> queryList = new ArrayList<Query>();
			NodeList nl = doc.getElementsByTagName("query");
			for( int i = 0; i < nl.getLength(); i++ ){
				
				Node n = nl.item(i);
				
				String queryId = null;
				String docId = null;
				String name = null;
				int begin = -1;
				int end = -1;
				
				Element element = (Element) n;
				queryId = element.getAttribute("id");
				
				NodeList childs = n.getChildNodes();
			 
				for (int j = 0; j < childs.getLength(); j++ ){
					
					Node m = childs.item(j);
					if  (m.getNodeName().equals("name") ){
						name = m.getTextContent();
					}else if( m.getNodeName().equals("docid")){
						docId = m.getTextContent();
					}else if( m.getNodeName().equals("beg")){
						begin = Integer.parseInt(m.getTextContent());
					}else if( m.getNodeName().equals("end")){
						end = Integer.parseInt(m.getTextContent());
					}
					
					
				}
				
				Query query = new Query(queryId,docId,name,begin,end);
				queryList.add(query);
			}
	
			return queryList;
		}else{
			Exception e = new Exception("no such query file");
			throw e ;
		}
	}
	
	//TEST test function
	public static void main(String[] args){
		QueryParser qp = new QueryParser("/largedata1/cmput696/students/lyao1/eval_script/dev.xml");
		try {
			List<Query> list = qp.getQueries();
			if (list == null){
				return;
			}
			System.out.println("Length:"+list.size());
			Query q1 = list.get(0);
			System.out.println("display one node");
			System.out.println("queryId:"+q1.getId());
			System.out.println("docid:"+q1.getDocid());
			System.out.println("name:"+q1.getName());
			System.out.println("begin:"+q1.getBegin());
			System.out.println("end:"+q1.getEnd());
			System.out.println("length:"+list.size());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	 
}
